﻿#include"TcpClient.h"
#include<thread>

//运行标志位
bool g_bRun = true;
//客户端数量
const int cCount = 10;
//发送线程数量
const int tCount = 4;
//客户端数组
TcpClient* client[cCount];

void cmdThread()
{
	while (true)
	{
		char cmdBuf[256] = {};
		scanf("%s", cmdBuf);
		if (0 == strcmp(cmdBuf, "exit"))
		{
			g_bRun = false;
			printf("退出cmdThread线程\n");
			break;
		}
		else 
		{
			printf("不支持的命令。\n");
		}
	}
}

void sendThread(int id)
{
	//4个线程 ID 1~4
	int c = cCount / tCount;
	if (c == 0)
	{
		c = 1;
	}

	int begin = (id - 1)*c;
	int end = id * c;

	for (int n = begin; n < end; n++)
	{
		client[n] = new TcpClient();
	}
	for (int n = begin; n < end; n++)
	{
		client[n]->connectHost("127.0.0.1", 4567);
		printf("thread<%d>,Connect=%d\n", id, n);
	}

	std::chrono::milliseconds t(5000);
	std::this_thread::sleep_for(t);

	//这里发送1000字节
	Login login[10];
	for (int n = 0; n < 10; n++)
	{
		strcpy(login[n].userName, "admin");
		strcpy(login[n].PassWord, "123456");
	}
	int len = sizeof(login);

	while (g_bRun)
	{
		for (int n = begin; n < end; n++)
		{
			client[n]->sendData(login, len);
			//client[n]->OnRun();

			//发送间隔
			//std::chrono::milliseconds t(50);
			//std::this_thread::sleep_for(t);
		}
	}

	for (int n = begin; n < end; n++)
	{
		client[n]->closeSocket();
	}
}

int main()
{
	//启动UI线程
	std::thread t1(cmdThread);
	t1.detach();

	//启动发送线程
	for (int n = 0; n < tCount; n++)
	{
		if ((n + 1) > cCount)
		{
			break;
		}
		std::thread task(sendThread, n + 1);
		task.detach();
	}

	while (g_bRun)
	{
		Sleep(500);
	}

	printf("已退出。\n");
	return 0;
}